import { Component, Vue, Watch } from 'vue-property-decorator' // @ is an alias to /src
import style from './Home.less'
import { menuList, getMenus } from '@/router'
import { State, Action, Mutation } from 'vuex-class'
import { RootState } from '@/store'
import { ElMenu } from 'element-ui/types/menu'

@Component({})
export default class Home extends Vue {
  @State((state: RootState) => state.user.accountName)
  private name!: string
  @State((state: RootState) => state.user.organizeName)
  private departmentName!: string

  @State((state: RootState) => state.user.dingUserId)
  private dingUserId!: string
  @State((state: RootState) => state.home.title)
  private homeTitle?: string

  // @Action('signflow/clearSignedData') private clearSignedData: any
  private defaultOpeneds = []
  public menuWidth = '220px'
  private headerHeight = '50px'
  private imageWidth = '30px'
  private isCollapse = false
  private defaultMenu = ''
  private gotInfo = false

  @Action('user/info') private userInfo!: any
  @Action('login/logout') private logout!: any
  @Action('user/ignoreBindingHint') private ignoreBindingHint!: any
  @Mutation('user/setStateData') private setStateData!: any

  protected render(h: any) {
    return (
      <el-container class={style.container}>
        <el-aside class={{ [style.aside]: true }} width={this.menuWidth}>
          <div
            style={{ height: this.headerHeight }}
            onClick={() => {
              this.$router.push({ name: 'homepage' })
            }}
            class={{ [style.title]: true, 'family-reg': true }}
          >
            <img
              src={require('@/assets/login-logo.png')}
              width={this.imageWidth}
              height={this.imageWidth}
            />
            电子印章申请系统
          </div>
          <div class={style.menu}>
            <el-menu
              class={style.elMenu}
              default-openeds={this.defaultOpeneds}
              collapse={this.isCollapse}
              style={{ width: this.menuWidth }}
              default-active={this.defaultMenu}
              collapse-transition={false}
              router
              ref="menu"
            >
              {menuList &&
                menuList.map(
                  (menu: any, i: number) =>
                    menu && (
                      <el-submenu index={`${i}`} key={i}>
                        <template slot="title">
                          <img
                            src={menu.icon}
                            width="24"
                            height="24"
                            style={{ marginRight: '5px' }}
                          />
                          <span slot="title">{menu.name}</span>
                        </template>
                        {menu.children &&
                          menu.children.map((child: any, index: number) => (
                            <el-menu-item
                              key={index}
                              index={child.meta.defaultPath || child.path}
                              style="padding-left:40px;"
                              class={{
                                'menu-item': true,
                                'family-YH': true,
                                'is-hold': this.isHold(child.meta.holds),
                              }}
                            >
                              <span slot="title">{child.meta.title}</span>
                            </el-menu-item>
                          ))}
                      </el-submenu>
                    )
                )}
            </el-menu>
          </div>
          <div
            style={{ width: this.menuWidth }}
            class={style.pack}
            onClick={() => {
              this.isCollapse = !this.isCollapse
            }}
          >
            <img
              src={require('@/assets/pack-up.png')}
              class={{ [style.packImg]: this.isCollapse }}
            />
            {this.isCollapse ? '' : <span>收起</span>}
          </div>
        </el-aside>
        <el-container>
          <el-header height={this.headerHeight}>
            <div class={style.path}>
              {!this.getName() && !this.isBack() && this.getMetaName()}
              {(this.getName() || (this.getMetaName() && this.isBack())) && (
                <span class={style.back} onClick={this.back}>
                  <i class="el-icon-arrow-left to-back" />
                  {this.getMetaName() || this.getName()}
                </span>
              )}
            </div>
            <div class={{ [style.info]: true }}>
              <el-tooltip
                class="help-tooltip color-9"
                effect="dark"
                content="技术支持中心"
                placement="bottom"
              >
                <div class={style.help} onClick={this.toHelp}>
                  ?
                </div>
              </el-tooltip>
              <span class={style.splice} />
              <span class={style.name} onClick={this.toUserInfo}>
                {this.gotInfo && !this.dingUserId && (
                  <div class={style.redPoint} />
                )}
                <img src={require('@/assets/avatar.png')} />
                {this.name || '--'}
              </span>
              <span class={style.splice} />
              {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
              <a onClick={this.quit} class={style.logout}>
                返回首页
              </a>
            </div>
          </el-header>
          <el-main>
            <div class={style.content}>
              <router-view />
            </div>
          </el-main>
        </el-container>
      </el-container>
    )
  }

  @Watch('isCollapse')
  private collapseChange(val: boolean) {
    if (val) {
      this.menuWidth = '50px'
    } else {
      this.menuWidth = '220px'
    }
  }

  // @Watch("$route.path")
  // private routeChange(path: string) {
  // }
  @Watch('$route.path')
  pathChange(val: any) {
    this.defaultMenu =
      (
        (getMenus().filter(
          (menu: any) => this.$route.path.indexOf(menu.path) > -1
        ) || [])[0] || {}
      ).path ||
      (
        (
          (getMenus().filter(
            (menu: any) =>
              this.$route.path.indexOf(menu.path.split(':')[0]) > -1
          ) || [])[0] || {}
        ).meta || {}
      ).defaultPath ||
      '/home/sealApply'
  }

  @Watch('homeTitle')
  private homeTitleChange(val: string) {
    console.warn(11, val)
    this.getName()
  }

  private created() {
    this.defaultMenu =
      (
        (getMenus().filter(
          (menu: any) => this.$route.path.indexOf(menu.path) > -1
        ) || [])[0] || {}
      ).path ||
      (
        (
          (getMenus().filter(
            (menu: any) =>
              this.$route.path.indexOf(menu.path.split(':')[0]) > -1
          ) || [])[0] || {}
        ).meta || {}
      ).defaultPath ||
      '/home/sealApply'
  }

  private mounted() {
    this.userInfo()
      .then((res: any) => {
        this.gotInfo = true
        if (!res.dingUserId && !res.ignoreBindingHint) {
          this.notifyBindDingUser()
        }
      })
      .catch((e: any) => {
        this.gotInfo = true
      })
    this.$nextTick(() => {
      // 展开所有菜单
      ;(this.$refs['menu'] as ElMenu) &&
        menuList.forEach((menu: any, index: number) => {
          ;(this.$refs['menu'] as ElMenu).open(`${index}`)
        })
    })
  }

  private isHold(holds: any[] | undefined) {
    if (holds && holds.length > 0) {
      return holds.indexOf(this.$route.name) !== -1
    }

    return false
  }

  private notifyBindDingUser() {
    this.$confirm('您好，检测到您还未绑定浙政钉账户，是否现在去绑定？', '', {
      cancelButtonText: '稍后',
      confirmButtonText: '绑定',
      type: 'warning',
      closeOnPressEscape: false,
      closeOnClickModal: false,
      showClose: false,
    })
      .then(() => {
        this.setStateData({
          bindDingUserVisible: true,
        })
      })
      .catch(() => {
        this.ignoreBindingHint()
      })
  }

  private quit() {
    // this.logout();
    this.$router.push({ name: 'homepage' })
  }

  private getMetaName() {
    return (
      (this.$route.meta.title &&
        this.$route.meta.title[this.$route.params.type]) ||
      this.$route.meta.title ||
      ''
    )
  }

  private isBack() {
    return !!this.$route.meta.back || !!this.$route.meta.isBack
  }

  private getName() {
    return (
      (
        (
          getMenus().find(
            (item: any) => this.$route.params.type === item.name
          ) || {}
        ).meta || {}
      ).title || ''
    )
  }

  private back() {
    if (
      !this.$route.meta.isBack &&
      (this.$route.meta.back || this.$route.params.type)
    ) {
      this.$router.push({
        name: this.$route.meta.back || this.$route.params.type,
        params: { type: this.$route.meta.type },
      })
    } else {
      this.$router.go(-1)
    }
  }

  private toHelp() {
    // console.log(window.config.helpWebUrl)
    window.open(`${window.location.origin}/support`, '_blank')
  }

  private toUserInfo() {
    this.$router.push({ name: 'userInfo' })
  }
}
